from django.contrib import admin
from .models import Goods
from django.http import HttpResponse
from django.utils.encoding import  escape_uri_path
from openpyxl import Workbook

g=Goods()
def sales_voluem(g):
    sales=g.price*g.sales
    return "{}销售额是：{}元".format(g.name,sales)
sales_voluem.short_description='商品销售额'

class BrandListFilter(admin.SimpleListFilter):
    title = '商品名称'
    parameter_name = 'brand_name'
    def lookups(self, request, model_admin):
        return (
            ('0',('Apple MacBook Pro')),
            ('1',('Apple iPhone')),
            ('2',('华为')),
            ('3',('小米')),
        )
    def queryset(self, request, queryset):
        if self.value() == '0':
            return queryset.filter(name__istartswith='Apple MacBook Pro')
        if self.value() == '1':
            return queryset.filter(name__istartswith='Apple iPhone')
        if self.value() == '2':
            return queryset.filter(name__istartswith='华为')
        if self.value() == '3':
            return queryset.filter(name__istartswith='小米')

# Register your models here.
@admin.register(Goods)
class GoodAdmin(admin.ModelAdmin):
    list_display = ('id','create_time','update_time','name','price','stock','sales')
    # list_display = ('id','name',sales_voluem)
    # list_display_links = ('id','name','price')
    list_filter = (BrandListFilter,)
    list_per_page = 8
    # list_editable = ('price')
    # search_fields = ('name')

    def download_excel(self, request, queryset):
        file_name='商品信息.xlsx'
        meta = self.model._meta
        field_names = [field.name for field in meta.fields]
        response = HttpResponse(content_type='application/msexcel')
        response['Content-Disposition'] = "attachment;file_name*=utf-8''{}".format(escape_uri_path(file_name))
        wb = Workbook()
        ws = wb.active
        ws.append(['ID', '创建时间', '更新时间', '商品名称', '价格', '库存', '销量'])
        for obj in queryset:
            for field in field_names:
                data = [getattr(obj, field) for filed in field_names]
                ws.append(data)
            wb.save(response)
            return response
                # download_excel_name = "下载商品信息"


    download_excel.short_description = "下载商品信息"
    actions=(download_excel,)
